﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Custom.Controls
{
    public partial class LoadingForm : Form
    {
        public LoadingForm(string description)
        {
            InitializeComponent();
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); //双缓冲

            this.lbDescription.Text = description.EndsWith("...") ? description : description + "...";
            this.Width = 124 + this.lbDescription.Text.Replace("...", "").Length * 15 + 70;
        }

        /// <summary>
        /// 设置窗体的Region
        /// </summary>
        public void SetWindowRegion()
        {
            GraphicsPath FormPath;
            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
            FormPath = GetRoundedRectPath(rect, 5);
            this.Region = new Region(FormPath);

        }
        /// <summary>
        /// 绘制圆角路径
        /// </summary>
        /// <param name="rect"></param>
        /// <param name="radius"></param>
        /// <returns></returns>
        private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)
        {
            int diameter = radius;
            Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
            GraphicsPath path = new GraphicsPath();

            // 左上角
            path.AddArc(arcRect, 180, 90);

            // 右上角
            arcRect.X = rect.Right - diameter;
            path.AddArc(arcRect, 270, 90);

            // 右下角
            arcRect.Y = rect.Bottom - diameter;
            path.AddArc(arcRect, 0, 90);

            // 左下角
            arcRect.X = rect.Left;
            path.AddArc(arcRect, 90, 90);
            path.CloseFigure();//闭合曲线
            return path;
        }

        /// <summary>
        /// 窗体size发生改变时重新设置Region属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Loader_Resize(object sender, EventArgs e)
        {
            SetWindowRegion();
        }

        /// <summary>
        /// 窗口关闭时，关闭遮罩
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadingFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        /// <summary>
        /// 设置文本内容
        /// </summary>
        /// <param name="description"></param>
        public void SetDescription(string description)
        {
            this.Invoke(new Action(() =>
            {
                this.lbDescription.Text = description.EndsWith("...") ? description : description + "...";
            }));            
        }
    }
}
